<?php

namespace Beike\Seller\Services;

use Beike\Seller\Models\Product;

class ProductService extends \Beike\Admin\Services\ProductService
{
    /**
     * @param array $data
     * @return Product
     */
    public function create(array $data): Product
    {
        $product = new Product;

        return $this->createOrUpdate($product, $data);
    }

    /**
     * @param Product $product
     * @param array   $data
     * @return Product
     */
    public function update(Product|\Beike\Models\Product $product, array $data): Product
    {
        return $this->createOrUpdate($product, $data);
    }

    /**
     * @param Product $product
     * @param array   $data
     * @return Product
     * @throws \Exception
     */
    protected function createOrUpdate(Product|\Beike\Models\Product $product, array $data): Product
    {
        $position_seller  = $data['position'];
        $productApprove   = current_seller_user()->seller->product_approve;
        $isUpdating       = $product->id > 0;
        if ($isUpdating) {
            $data['position'] = $product->position;
            // 审核通过的商品名称不允许修改，审核不通过的商品可以修改，并且修改后需要继续审核。
            if ($product->approved_at && $product->approved_status) {
                $descriptions = $product->descriptions()->pluck('name', 'locale')->toArray();
                foreach (languages() as $language) {
                    $data['descriptions'][$language]['name'] = $descriptions[$language];
                }
            } else {
                $product->approved_at     = null;
                $product->approved_status = 0;
            }
            // 修改商品时商品状态根据是否已审核通过确定是否可修改上下架状态
            if (! $product->approved_at || ! $product->approved_status) {
                unset($data['active']);
            }
        } else {
            // 创建商品时默认为未上架
            $data['position']         = 0;
            $product->approved_at     = $productApprove ? null : now();
            $product->approved_status = $productApprove ? 0 : 1;
            if ($productApprove) {
                $product->active = 0;
            }
        }

        $product = parent::createOrUpdate($product, $data);
        $product->sellerCategories()->sync($data['seller_categories'] ?? []);

        $product->position_seller     = $position_seller;
        $product->date_available_from = $data['date_available_from'] ?? null;
        $product->date_available_to   = $data['date_available_to']   ?? null;
        $product->seller_id           = current_seller_user()->seller_id;
        $product->save();

        return $product;
    }
}
